package com.ruoyi.framework.config;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {



    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey("abcdefghijklmnopqrstuvwxyz")
                .parseClaimsJws(token)
                .getBody();
    }
    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        List<String> list = request.getHeaders().get("cookie");
        String[] split = list.get(0).split("; ");

        // 将分割后的字符串转换为 Map<String, String>
        Map<String, String> resultMap = Arrays.stream(split)
                .map(s -> s.split("=", 2))  // 分割成键和值，最多分割一次
                .collect(Collectors.toMap(
                        parts -> parts[0],  // 使用第一个部分作为键
                        parts -> parts[1],  // 使用第二个部分作为值
                        (oldValue, newValue) -> newValue  // 处理重复键的情况，使用新的值覆盖旧的值
                ));
        Claims claims = parseToken(resultMap.get("Admin-Token"));
        RedisCache cache = SpringUtils.getBean(RedisCache.class);
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = getTokenKey(uuid);
        LoginUser user = cache.getCacheObject(userKey);

        config.getUserProperties().put("user",user);
    }
}
